package com.example.om_export.system.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wb-ycl473317
 */
@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean<Filter> corsFilter(){
        FilterRegistrationBean<Filter> filterFilterRegistrationBean = new FilterRegistrationBean<>();
        filterFilterRegistrationBean.setFilter((request,response,chain)->{
            HttpServletResponse res = (HttpServletResponse) response;
            HttpServletRequest req = (HttpServletRequest) request;
            res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
            res.setHeader("Access-Control-Allow-Credentials","true");
            String options = "OPTIONS";
			if(options.equals(req.getMethod())){
                res.setHeader("Access-Control-Allow-Headers","Content-Type");
                res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
                // 预检请求有效期30分钟，这样30分钟内就不会发起第二次预检请求
                res.setHeader("Access-Control-Max-Age", "1800");
			}else{
			    // 如果是options请求就不需要后续的过滤了，防止被shiro等安全框架拦截
                chain.doFilter(request,response);
            }
        });
        return filterFilterRegistrationBean;
    }
}
